package io.github.wslxm.springbootplus2.utils;

import cn.hutool.core.lang.Dict;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.Method;
/**
 * uri 获取工具类
 *
 * @date 2025/9/25 11:36
 * @return
 */
public class XjUriUtil {


    /**
     * 获取类上的 uri
     *
     * @param classInfo 请求类
     * @return puri
     */
    public static String getClassUri(Class<?> classInfo) {
        RequestMapping requestMappingClass = classInfo.getDeclaredAnnotation(RequestMapping.class);
        if (requestMappingClass == null) {
            return  "";
        }
        return requestMappingClass.value()[0];
    }


    /**
     * 获取接口上的 uri
     *
     * @param pUri   类上的 uri
     * @param method 当前返回
     * @return
     */
    public static Dict getMethodUri(String pUri, Method method) {
        String uri = null;
        String requestMethod = null;
        RequestMapping requestMapping = method.getAnnotation(RequestMapping.class);
        if (requestMapping != null) {
            uri = pUri + getRequestMappingValue(requestMapping.value());
            requestMethod = requestMapping.method()[0].name();
        }
        GetMapping getMapping = method.getAnnotation(GetMapping.class);
        if (uri == null && getMapping != null) {
            uri = pUri + getRequestMappingValue(getMapping.value());
            requestMethod = RequestMethod.GET.name();
        }
        PostMapping postMapping = method.getAnnotation(PostMapping.class);
        if (uri == null && postMapping != null) {
            uri = pUri + getRequestMappingValue(postMapping.value());
            requestMethod = RequestMethod.POST.name();
        }
        PutMapping putMapping = method.getAnnotation(PutMapping.class);
        if (uri == null && putMapping != null) {
            uri = pUri + getRequestMappingValue(putMapping.value());
            requestMethod = RequestMethod.PUT.name();
        }
        DeleteMapping deleteMapping = method.getAnnotation(DeleteMapping.class);
        if (uri == null && deleteMapping != null) {
            uri = pUri + getRequestMappingValue(deleteMapping.value());
            requestMethod = RequestMethod.DELETE.name();
        }
        return Dict.create().set("uri", uri).set("requestMethod", requestMethod);
    }



    /**
     * 判断是否有/, 没有则追加
     *
     * @return
     */
    private static String getRequestMappingValue(String[] requestMappingValues) {
        String requestMappingValue = requestMappingValues.length > 0 ? requestMappingValues[0] : "";
        if (StringUtils.isNotBlank(requestMappingValue) && requestMappingValue.charAt(0) != '/') {
            return "/" + requestMappingValue;
        }
        return requestMappingValue;
    }
}
